<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Hash;
use Session;

class LoginController extends Controller
{
    //执行登录
    public function login(Request $request)
    {
    	//判断路径类型是否为post
    	if($request -> isMethod('post'))
    	{
    		// 进行数据验证
    		// $this -> validate($request,[
    		// 	'uname' => 'required',
    		// 	'upass' => 'required',
    		// 	],[
    		// 	'name.required' => '用户名不能为空',
    		// 	'password.required' => '密码不能为空',
    		// 	]);
    		$data = $request -> except('_token');
    		//查询数据
    		$res = DB::table('users') -> where('name',$data['uname']) -> orwhere('email',$data['uname'])-> first();
    		if(!$res)
    		{
    			return back() -> with(['info' => '用户名或密码错误']);
    		}

    		//密码进行加密
    		$r = Hash::check($data['upass'],$res -> password);
    		if(!$r)
    		{
    			return back() -> with(['info' => '用户名或密码错误']);
    		}
    		//将管理员信息存入session中
    		Session::put('user',$res);

    		return redirect('myZone') -> with(['info' => '登录成功']);
    	}
    	// return view('admin.login');
    }

    //退出登录
    public function logout()
    {
        Session::forget('user');
        Session::forget('uid');
    	return redirect('/') -> with(['info' => '退出成功']);
    }

    //注册
    public function register(Request $request){
    	if($request -> isMethod('POST'))
        {
            $this -> validate($request,[
                'repass' => 'required',
                ],[
                'email.unique' => '该邮箱已被注册',
                ]);

            if($request['password'] != $request['repass'])
            {
                return back() -> with(['info' => '密码和确认密码不一致']);
            }
            $data = $request -> except('_token','repass');
            $data['password'] = Hash::make($data['password']);
            $time = time();
            $data['created_at'] = date('Y-m-d H:i:s',$time);
            $data['updated_at'] = date('Y-m-d H:i:s',$time);
            $data['remember_token'] = str_random(50);
            $res = DB::table('users') -> insertGetId($data);
            DB::table('password_resets') -> where('user_id', $res) -> insert(['email' => $data['email'],'token' => $data['remember_token'],'created_at' => $data['created_at']]);
        }
        return view('home.login');
    }
    
}
